import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class Product {
  final String name;

  const Product({required this.name});
}

typedef CartChangeCallBack = Function(Product product, bool inChart);

class ShoppingListItem extends StatelessWidget {
  final Product product;
  final bool inChart;
  final CartChangeCallBack onCartChanged;

  ShoppingListItem({
    required this.product,
    required this.inChart,
    required this.onCartChanged,
  }) : super(key: ObjectKey(product));

  @override
  Widget build(BuildContext context) {
    return ListTile(
      onTap: () {
        onCartChanged(product, inChart);
      },
      leading: CircleAvatar(
        backgroundColor: _getColor(context),
        child: Text(product.name[0]),
      ),
      title: Text(
        product.name,
        style: _getTextStyle(context),
      ),
    );
  }

  Color _getColor(BuildContext context) {
    return inChart ? Colors.black54 : Theme.of(context).primaryColor;
  }

  TextStyle? _getTextStyle(BuildContext context) {
    if (!inChart) return null;
    return const TextStyle(
        color: Colors.black54, decoration: TextDecoration.lineThrough);
  }
}

class ShoppingList extends StatefulWidget {
  final List<Product> products;

  const ShoppingList({super.key, required this.products});

  @override
  State<StatefulWidget> createState() => _ShoppingListState();
}

class _ShoppingListState extends State<ShoppingList> {
  final _shopCart = <Product>{};

  void _handleCardChanged(Product product, bool inCart) {
    setState(() {
      if (!inCart) {
        _shopCart.add(product);
      } else {
        _shopCart.remove(product);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Shopping List"),
      ),
      body: ListView(
        padding: const EdgeInsets.symmetric(vertical: 8),
        children: widget.products.map((product) {
          return ShoppingListItem(
              product: product,
              inChart: _shopCart.contains(product),
              onCartChanged: _handleCardChanged);
        }).toList(),
      ),
    );
  }
}

class CategoryPage extends StatelessWidget {
  const CategoryPage({super.key});

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
          child: ShoppingList(
        products: [
          Product(name: "Eggs"),
          Product(name: "Flour"),
          Product(name: "Chocolate chips"),
        ],
      )),
    );
  }
}
